# -*- coding: utf-8 -*-

import json

from django.utils.decorators import method_decorator
from django.utils.encoding import smart_unicode
from django.views.generic import TemplateView

from common.console import db as user_db
from common.risk import db as risky_db
from common.utils import track_logging
from common.utils.api import token_required
from common.utils.decorator import response_wrapper
from common.utils.tz import (
    utc_to_local_str
)

_LOGGER = track_logging.getLogger(__name__)


class RiskCardView(TemplateView):
    def get(self, req):
        query_dct = req.GET.dict()

        cond = user_db.get_mchids_filter_by_user(req.user_id)
        if cond and query_dct.get('mch_id') is None:
            query_dct['mch_id'] = cond
        items, total_count = risky_db.list_risky_card(query_dct)

        resp_items = []
        for item in items:
            data = item.as_dict()
            data['created_at'] = utc_to_local_str(data['created_at'])
            data['updated_at'] = utc_to_local_str(data['updated_at'])
            data['mch_id'] = int(data['mch_id'])
            resp_items.append(data)
        return {'list': resp_items, 'page': query_dct.get('$page', 1),
                'size': len(resp_items), 'total_count': total_count}

    def post(self, req):
        query_dct = json.loads(req.body)
        query_dct['admin'] = req.user.username
        card = risky_db.create_risky_card(query_dct)
        return {}

    @method_decorator(response_wrapper)
    @method_decorator(token_required)
    def dispatch(self, *args, **kwargs):
        return super(RiskCardView, self).dispatch(*args, **kwargs)


class SingleRiskCardView(TemplateView):
    def get(self, req, card_id):
        card = risky_db.get_risky_card(id=int(card_id))

        data = card.as_dict()
        data['created_at'] = utc_to_local_str(data['created_at'])
        data['updated_at'] = utc_to_local_str(data['updated_at'])
        data['mch_id'] = int(data['mch_id'])
        return data

    def post(self, req, card_id):
        return self.put(req, card_id)

    def put(self, req, card_id):
        query_dct = json.loads(smart_unicode(req.body))
        query_dct['admin'] = req.user.username
        risky_db.upsert_risky_card(query_dct, int(card_id))
        _LOGGER.info('upsert card withdraw param : %s %s' % (card_id, query_dct))
        return {}

    def delete(self, req, card_id):
        risky_db.delete_risky_card(int(card_id))
        _LOGGER.info('delete risky card: %s, user: %s', card_id, req.user_id)
        return {}

    @method_decorator(response_wrapper)
    @method_decorator(token_required)
    def dispatch(self, *args, **kwargs):
        return super(SingleRiskCardView, self).dispatch(*args, **kwargs)


@token_required
@response_wrapper
def get_user_list(req):
    query_dct = req.GET.dict()
    items, total_count = risky_db.list_risky_user(query_dct)

    resp_items = []
    for item in items:
        data = item.as_dict()
        data['created_at'] = utc_to_local_str(data['created_at'])
        data['updated_at'] = utc_to_local_str(data['updated_at'])
        resp_items.append(data)
    return {'list': resp_items, 'page': query_dct.get('$page', 1),
            'size': len(resp_items), 'total_count': total_count}


@token_required
@response_wrapper
def delete_black_card(req, card_id):
    risky_db.delete_risky_card(int(card_id))
    _LOGGER.info('delete risky card: %s, user: %s', card_id, req.user_id)
    return {}


@token_required
@response_wrapper
def update_user_status(req, user_id):
    query_dct = json.loads(smart_unicode(req.body))
    query_dct['admin'] = req.user.username
    risky_db.upsert_risky_user(query_dct, int(user_id))
    return {}


@token_required
@response_wrapper
def get_user_ip(req, user_id):
    resp_items = []
    items = risky_db.get_user_ip(int(user_id))
    for item in items:
        data = item.as_dict()
        data['created_at'] = utc_to_local_str(data['created_at'])
        resp_items.append(data)
    return resp_items


@token_required
@response_wrapper
def get_user_info(req, user_id):
    user_info = risky_db.get_risky_user(int(user_id))
    return user_info.as_dict()
